﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.IO;
using System.Windows.Forms;
using EntityTools.Interface;

namespace EntityTools
{
    public partial class MainForm : Form
    {
        public static string bakFile = "";

        public MainForm()
        {
            InitializeComponent();
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            comboBoxDbType.Items.Add("MySql");
            comboBoxDbType.Items.Add("Sqlite");
            txtFilePath.Click += new EventHandler(txtFilePath_Click);
        }

        private void comboBoxDbType_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (comboBoxDbType.SelectedItem.ToString() == "Sqlite")
            {
                labelAddress.Text = "目标数据库";
                txtUserName.Enabled = false;
                txtPassword.Enabled = false;
                txtTargetDb.Enabled = false;
                txtIPAddress.Click += new EventHandler(txtIPAddress_Click);
            }
            else
            {
                labelAddress.Text = "服务器地址";
                txtUserName.Enabled = true;
                txtPassword.Enabled = true;
                txtTargetDb.Enabled = true;
                txtIPAddress.Click -= new EventHandler(txtIPAddress_Click);
            }
        }

        private void txtIPAddress_Click(object sender, EventArgs e)
        {
            openFileDialog.Filter = "SQLite数据库文件(*.db)|*.db|所有文件(*.*)|*.*";
            DialogResult result = openFileDialog.ShowDialog();

            if (result == System.Windows.Forms.DialogResult.OK)
            {
                txtIPAddress.Text = openFileDialog.FileName.Trim();
            }
        }

        private void txtFilePath_Click(object sender, EventArgs e)
        {
            openFileDialog.FileName = "Entity.cs";
            openFileDialog.CheckFileExists = false;
            openFileDialog.Filter = "实体类文件(*.cs)|*.cs|所有文件(*.*)|*.*";
            DialogResult result = openFileDialog.ShowDialog();

            if (result == System.Windows.Forms.DialogResult.OK)
            {
                txtFilePath.Text = openFileDialog.FileName.Trim();
            }
        }

        private void btnOK_Click(object sender, EventArgs e)
        {
            //检查输入合法性
            string check = checkInput();
            if (check != "") { MessageBox.Show(check); return; }

            try
            {
                if (comboBoxDbType.SelectedItem.ToString() == "Sqlite")
                {
                    SqliteDbInfo sqlite = new SqliteDbInfo();
                    writeEntityFile(txtFilePath.Text.Trim(), txtIPAddress.Text.Trim(), sqlite);
                }
                else if (comboBoxDbType.SelectedItem.ToString() == "MySql")
                {
                    MysqlDbInfo mysql = new MysqlDbInfo(txtIPAddress.Text.Trim(), txtTargetDb.Text.Trim(), txtUserName.Text.Trim(), txtPassword.Text.Trim());
                    writeEntityFile(txtFilePath.Text.Trim(), txtTargetDb.Text.Trim(), mysql);
                }

                MessageBox.Show("生成成功！");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        //检查输入合法性
        private string checkInput()
        {
            string result = "";

            if (comboBoxDbType.SelectedIndex == -1)
            {
                result = "请选择数据库类型！";
            }
            else if (comboBoxDbType.SelectedItem.ToString() == "Sqlite")
            {
                if (txtIPAddress.Text.Trim() == "") result = "请选择目标数据库！";
                else if (txtFilePath.Text.Trim() == "") result = "请选择实体类文件存放位置！";
            }
            else
            {
                if (txtIPAddress.Text.Trim() == "") result = "请填写数据库服务器地址！";
                else if (txtUserName.Text.Trim() == "") result = "请填写数据库用户名！";
                else if (txtPassword.Text.Trim() == "") result = "请填写数据库密码！";
                else if (txtTargetDb.Text.Trim() == "") result = "请填写目标数据库！";
                else if (txtFilePath.Text.Trim() == "") result = "请选择实体类文件存放位置！";
            }

            return result;
        }

        private void writeEntityFile(string entityFilePath, string dbName, IDatabaseInfo dbInfo)
        {
            //复制原有实体类文件，以便读取原有描述信息
            if (File.Exists(entityFilePath))
            {
                bakFile = entityFilePath + ".bak";
                File.Copy(entityFilePath, bakFile, true);
            }

            //生成新的实体类文件，如果已经存在则覆盖
            StreamWriter sw = new StreamWriter(entityFilePath, false, Encoding.Default);

            //名称空间开始
            sw.WriteLine("using System;");
            sw.WriteLine("using System.Data;");
            sw.WriteLine("using WAF.Data;");
            sw.WriteLine("");
            sw.WriteLine("namespace WAF.Data.EntityClass");
            sw.WriteLine("{");

            StringBuilder sb = new StringBuilder();

            //实体类
            foreach (string tbName in dbInfo.GetTablesFromDb(dbName))
            {
                //类开头
                sw.WriteLine("  public class " + tbName + " : WAF.Data.EntityBase");
                sw.WriteLine("  {");

                /*
                //rowid字段信息
                sw.WriteLine("     [EntityFieldAttribute(0, true, true, true, false, DbType.Int64, 0, \"id\")]");
                sw.WriteLine("     public int rowid { get; set; }");
                sw.WriteLine();
                */

                foreach (DbFieldInfo fInfo in dbInfo.GetFieldsFromTable(tbName))
                {
                    //属性
                    sb.Clear();
                    sb.Append("     [EntityFieldAttribute(")
                      .Append(fInfo.Sequence).Append(", ")          //字段顺序
                      .Append(fInfo.IsPrimeKey).Append(", ")        //是否主键
                      .Append(fInfo.IsUnique).Append(", ")          //是否唯一
                      .Append(fInfo.IsNotNull).Append(", ")         //是否可空
                      .Append(fInfo.IsForeignKey).Append(", ")      //是否外键
                      .Append(fInfo.DatabaseType).Append(", ")      //数据类型
                      .Append(fInfo.Size).Append(", \"")            //字段长度
                      .Append(fInfo.Description).Append("\"");      //字段描述

                    //关联表信息
                    if (fInfo.RelTable != "")
                    {
                        sb.Append(", \"")
                          .Append(fInfo.RelTable).Append("\", \"")
                          .Append(fInfo.RelIdField).Append("\", \"")
                          .Append(fInfo.RelNameField).Append("\"");
                    }

                    sb.Append(")]");
                    sw.WriteLine(sb.ToString());

                    //字段名
                    sb.Clear();
                    sb.Append("     public ").Append(fInfo.FieldType).Append(" ").Append(fInfo.Name).Append(" { get; set; }");
                    sw.WriteLine(sb.ToString());

                    sw.WriteLine();
                }

                //类结束
                sw.WriteLine("  }");
                sw.WriteLine();
            }

            //名称空间结尾
            sw.WriteLine("}");

            //实体类文件写结束
            sw.Close();
        }
    }
}
